package com.bf.electroplating.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bf.electroplating.login.UserContext;
import com.bf.electroplating.login.UserDetail;
import com.bf.electroplating.pojo.dto.IdDTO;
import com.bf.electroplating.pojo.dto.comFireEquipmentInventory.ComFireEquipmentInventoryDTO;
import com.bf.electroplating.pojo.dto.comFireEquipmentInventory.ComFireEquipmentInventoryVO;
import com.bf.electroplating.pojo.entity.ComCompany;
import com.bf.electroplating.pojo.entity.ComEmergencyMaterialInventory;
import com.bf.electroplating.pojo.entity.ComFireEquipmentInventory;
import com.bf.electroplating.pojo.vo.ResultVO;
import com.bf.electroplating.service.ComCompanyService;
import com.bf.electroplating.service.IComFireEquipmentInventoryService;
import com.bf.electroplating.util.idempotent.Idempotent;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 企业消防器材清单表 前端控制器
 * </p>
 *
 * @author gzd
 * @since 2025-10-27
 */
@Slf4j
@RestController
@RequestMapping("/electroplating/comFireEquipmentInventory")
@Tag(name = "企业消防器材清单管理", description = "企业消防器材清单管理相关接口")
public class ComFireEquipmentInventoryController {

    @Resource
    private IComFireEquipmentInventoryService fireEquipmentInventoryService;
    @Resource
    private ComCompanyService  comCompanyService;

    @PostMapping("/page")
    @Operation(summary = "分页查询消防器材清单列表", description = "分页查询消防器材清单列表")
    public ResultVO<Page<ComFireEquipmentInventoryVO>> pageList(@RequestBody ComFireEquipmentInventoryDTO queryDTO) {
        try {
            UserDetail currentUser = UserContext.getUser();
            if (currentUser == null) {
                return ResultVO.fail("用户未登录");
            }
            Page<ComFireEquipmentInventory> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
            LambdaQueryWrapper<ComFireEquipmentInventory> wrapper = new LambdaQueryWrapper<>();
            
            // 根据企业ID过滤
            if (CollectionUtils.isEmpty(currentUser.getParkFunctionIds())) {
                wrapper.eq(ComFireEquipmentInventory::getCompanyId, currentUser.getCompanyId());
            }

            wrapper.eq(ComFireEquipmentInventory::getDelFlag, "0");
            
            // 动态查询条件
            if (StringUtils.hasText(queryDTO.getCompanyId())) {
                wrapper.eq(ComFireEquipmentInventory::getCompanyId, queryDTO.getCompanyId());
            }
            if (StringUtils.hasText(queryDTO.getWorkshopName())) {
                wrapper.like(ComFireEquipmentInventory::getWorkshopName, queryDTO.getWorkshopName());
            }
            if (StringUtils.hasText(queryDTO.getEquipmentType())) {
                wrapper.like(ComFireEquipmentInventory::getEquipmentType, queryDTO.getEquipmentType());
            }
            if (StringUtils.hasText(queryDTO.getMaintenanceStatus())) {
                wrapper.eq(ComFireEquipmentInventory::getMaintenanceStatus, queryDTO.getMaintenanceStatus());
            }
            if (StringUtils.hasText(queryDTO.getStatus())) {
                wrapper.eq(ComFireEquipmentInventory::getStatus, queryDTO.getStatus());
            }
            
            wrapper.orderByDesc(ComFireEquipmentInventory::getCreateTime);
            
            Page<ComFireEquipmentInventory> result = fireEquipmentInventoryService.page(page, wrapper);
            Page<ComFireEquipmentInventoryVO>  pageVO = new Page<>();
            pageVO.setTotal(result.getTotal());
            pageVO.setRecords(result.getRecords().stream().map(i->{
                ComFireEquipmentInventoryVO comFireEquipmentInventoryVO = new ComFireEquipmentInventoryVO();
                BeanUtils.copyProperties(i,comFireEquipmentInventoryVO);
                comFireEquipmentInventoryVO.setCompanyName(comFireEquipmentInventoryVO.getCompanyName());
                ComCompany comCompany = comCompanyService.getById(comFireEquipmentInventoryVO.getCompanyId());
                if (comCompany != null) {
                    comFireEquipmentInventoryVO.setCompanyName(comCompany.getCompanyName());
                }
                return comFireEquipmentInventoryVO;
            }).collect(Collectors.toList()));
            return ResultVO.ok(pageVO);
        } catch (Exception e) {
            log.error("分页查询消防器材清单列表异常：", e);
            return ResultVO.fail("查询失败：" + e.getMessage());
        }
    }

    @Idempotent
    @PostMapping("/save")
    @Operation(summary = "新增消防器材清单", description = "新增消防器材清单")
    public ResultVO<String> save(@RequestBody @Validated ComFireEquipmentInventory dto) {
        try {
            UserDetail currentUser = UserContext.getUser();
            if (currentUser == null) {
                return ResultVO.fail("用户未登录");
            }

            // 设置基础信息
            dto.setId(null);
            dto.setParkId(currentUser.getParkId());
            dto.setCompanyId(currentUser.getCompanyId());
            dto.setCreateBy(currentUser.getId());
            dto.setCreateTime(LocalDateTime.now());
            dto.setDelFlag("0");
            
            if (!StringUtils.hasText(dto.getStatus())) {
                dto.setStatus("1");
            }
            if (!StringUtils.hasText(dto.getMaintenanceStatus())) {
                dto.setMaintenanceStatus("1");
            }

            boolean result = fireEquipmentInventoryService.save(dto);
            if (result) {
                return ResultVO.ok("新增成功");
            } else {
                return ResultVO.fail("新增失败");
            }
        } catch (Exception e) {
            log.error("新增消防器材清单异常：", e);
            return ResultVO.fail("新增失败：" + e.getMessage());
        }
    }

    @PostMapping("/update")
    @Operation(summary = "修改消防器材清单", description = "修改消防器材清单")
    public ResultVO<String> update(@RequestBody @Validated ComFireEquipmentInventory dto) {
        try {
            UserDetail currentUser = UserContext.getUser();
            if (currentUser == null) {
                return ResultVO.fail("用户未登录");
            }

            if (!StringUtils.hasText(dto.getId())) {
                return ResultVO.fail("ID不能为空");
            }

            // 验证数据是否存在
            ComFireEquipmentInventory existing = fireEquipmentInventoryService.getById(dto.getId());
            if (existing == null) {
                return ResultVO.fail("数据不存在");
            }
            if (CollectionUtils.isEmpty(currentUser.getParkFunctionIds())) {

            // 验证企业权限
            if (!currentUser.getCompanyId().equals(existing.getCompanyId())) {
                return ResultVO.fail("无权限操作此数据");
            }
            }

            // 设置更新信息
            dto.setUpdateBy(currentUser.getId());
            dto.setUpdateTime(LocalDateTime.now());

            boolean result = fireEquipmentInventoryService.updateById(dto);
            if (result) {
                return ResultVO.ok("修改成功");
            } else {
                return ResultVO.fail("修改失败");
            }
        } catch (Exception e) {
            log.error("修改消防器材清单异常：", e);
            return ResultVO.fail("修改失败：" + e.getMessage());
        }
    }

    @PostMapping("/delete")
    @Operation(summary = "删除消防器材清单", description = "删除消防器材清单")
    public ResultVO<String> delete(@RequestBody List<String> ids) {
        try {
            UserDetail currentUser = UserContext.getUser();
            if (currentUser == null) {
                return ResultVO.fail("用户未登录");
            }

            if (ids == null || ids.isEmpty()) {
                return ResultVO.fail("请选择要删除的数据");
            }

            // 验证数据权限并逻辑删除
            LambdaQueryWrapper<ComFireEquipmentInventory> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(ComFireEquipmentInventory::getId, ids);
            wrapper.eq(ComFireEquipmentInventory::getDelFlag, "0");

            List<ComFireEquipmentInventory> list = fireEquipmentInventoryService.list(wrapper);

            // 批量逻辑删除
            for (ComFireEquipmentInventory item : list) {
                item.setDelFlag("1");
                item.setUpdateBy(currentUser.getId());
                item.setUpdateTime(LocalDateTime.now());
            }

            boolean result = fireEquipmentInventoryService.updateBatchById(list);
            if (result) {
                return ResultVO.ok("删除成功");
            } else {
                return ResultVO.fail("删除失败");
            }
        } catch (Exception e) {
            log.error("删除消防器材清单异常：", e);
            return ResultVO.fail("删除失败：" + e.getMessage());
        }
    }

    @PostMapping("/detail")
    @Operation(summary = "获取消防器材清单详情", description = "获取消防器材清单详情")
    public ResultVO<ComFireEquipmentInventory> getDetail(@RequestBody IdDTO idDTO) {
        try {
            UserDetail currentUser = UserContext.getUser();
            if (currentUser == null) {
                return ResultVO.fail("用户未登录");
            }

            if (!StringUtils.hasText(idDTO.getId())) {
                return ResultVO.fail("ID不能为空");
            }

            ComFireEquipmentInventory result = fireEquipmentInventoryService.getById(idDTO.getId());
            if (result == null) {
                return ResultVO.fail("数据不存在");
            }
            if (CollectionUtils.isEmpty(currentUser.getParkFunctionIds())) {

                // 验证企业权限
                if (!currentUser.getCompanyId().equals(result.getCompanyId())) {
                    return ResultVO.fail("无权限查看此数据");
                }
            }

            return ResultVO.ok(result);
        } catch (Exception e) {
            log.error("获取消防器材清单详情异常：", e);
            return ResultVO.fail("查询失败：" + e.getMessage());
        }
    }

//    @GetMapping("/list")
//    @Operation(summary = "获取消防器材清单列表", description = "获取消防器材清单列表")
//    public ResultVO<List<ComFireEquipmentInventory>> list() {
//        try {
//            UserDetail currentUser = UserContext.getUser();
//            if (currentUser == null) {
//                return ResultVO.fail("用户未登录");
//            }
//
//            LambdaQueryWrapper<ComFireEquipmentInventory> wrapper = new LambdaQueryWrapper<>();
//            wrapper.eq(ComFireEquipmentInventory::getCompanyId, currentUser.getCompanyId());
//            wrapper.eq(ComFireEquipmentInventory::getDelFlag, "0");
//            wrapper.eq(ComFireEquipmentInventory::getStatus, "1");
//            wrapper.orderByDesc(ComFireEquipmentInventory::getCreateTime);
//
//            List<ComFireEquipmentInventory> result = fireEquipmentInventoryService.list(wrapper);
//            return ResultVO.ok(result);
//        } catch (Exception e) {
//            log.error("获取消防器材清单列表异常：", e);
//            return ResultVO.fail("查询失败：" + e.getMessage());
//        }
//    }

//    @GetMapping("/maintenance")
//    @Operation(summary = "获取需要维护的消防器材", description = "获取需要维护的消防器材")
//    public ResultVO<List<ComFireEquipmentInventory>> getMaintenanceEquipment() {
//        try {
//            UserDetail currentUser = UserContext.getUser();
//            if (currentUser == null) {
//                return ResultVO.fail("用户未登录");
//            }
//
//            LambdaQueryWrapper<ComFireEquipmentInventory> wrapper = new LambdaQueryWrapper<>();
//            wrapper.eq(ComFireEquipmentInventory::getCompanyId, currentUser.getCompanyId());
//            wrapper.eq(ComFireEquipmentInventory::getDelFlag, "0");
//            wrapper.eq(ComFireEquipmentInventory::getStatus, "1");
//            wrapper.in(ComFireEquipmentInventory::getMaintenanceStatus, "2", "3");
//            wrapper.orderByAsc(ComFireEquipmentInventory::getNextMaintenanceDate);
//
//            List<ComFireEquipmentInventory> result = fireEquipmentInventoryService.list(wrapper);
//            return ResultVO.ok(result);
//        } catch (Exception e) {
//            log.error("获取需要维护的消防器材异常：", e);
//            return ResultVO.fail("查询失败：" + e.getMessage());
//        }
//    }

//    @PostMapping("/updateMaintenance")
//    @Operation(summary = "更新维护信息", description = "更新消防器材维护信息")
//    public ResultVO<String> updateMaintenance(@RequestBody ComFireEquipmentInventory dto) {
//        try {
//            UserDetail currentUser = UserContext.getUser();
//            if (currentUser == null) {
//                return ResultVO.fail("用户未登录");
//            }
//
//            if (!StringUtils.hasText(dto.getId())) {
//                return ResultVO.fail("ID不能为空");
//            }
//
//            // 验证数据是否存在
//            ComFireEquipmentInventory existing = fireEquipmentInventoryService.getById(dto.getId());
//            if (existing == null) {
//                return ResultVO.fail("数据不存在");
//            }
//
//            // 验证企业权限
//            if (!currentUser.getCompanyId().equals(existing.getCompanyId())) {
//                return ResultVO.fail("无权限操作此数据");
//            }
//
//            // 只更新维护相关字段
//            existing.setLastMaintenanceDate(dto.getLastMaintenanceDate());
//            existing.setNextMaintenanceDate(dto.getNextMaintenanceDate());
//            existing.setMaintenanceStatus(dto.getMaintenanceStatus());
//            existing.setUpdateBy(currentUser.getId());
//            existing.setUpdateTime(LocalDateTime.now());
//
//            boolean result = fireEquipmentInventoryService.updateById(existing);
//            if (result) {
//                return ResultVO.ok("维护信息更新成功");
//            } else {
//                return ResultVO.fail("维护信息更新失败");
//            }
//        } catch (Exception e) {
//            log.error("更新维护信息异常：", e);
//            return ResultVO.fail("更新失败：" + e.getMessage());
//        }
//    }
}
